package org.springframework.test.zhaohui.service;

import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * DataAccessService
 *
 * @author zhaohui
 */
@Service
public class DataAccessService extends ApplicationObjectSupport {

	@Resource
	private JdbcTemplate jdbcTemplate;

	@Transactional(rollbackFor = Exception.class)
	public void exec() {
		String insertSqlPattern = "insert into demo_user (user_name, age, gender) values ('%s', '%s', %s)";
		int count = 0;
		for (int i = 1; i <= 2; i++) {
			String sql = String.format(insertSqlPattern, "zhangsan" + i, i * 10, 1);
			System.out.println(sql);
			jdbcTemplate.execute(sql);
			count += 1;
		}
		System.out.println("Execute finished。count : " + count);
//		getApplicationContext().getBean(DataAccessService.class).run();
		this.run();
		throw new RuntimeException();
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void run() {
		String insertSqlPattern = "insert into demo_user (user_name, age, gender) values ('%s', '%s', %s)";
		String sql = String.format(insertSqlPattern, "lisi" + 100, 10, 0);
		jdbcTemplate.execute(sql);
//		if (0 == 1/2) {
//			throw new RuntimeException();
//		}
		sql = String.format(insertSqlPattern, "lisi" + 100, 10, 0);
		System.out.println(sql);
		jdbcTemplate.execute(sql);

	}

}
